﻿using SocketControl.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;

namespace SocketControl.Iocp.Pool
{
    public class SocketAsyncEventArgsPool
    {
        private Queue<SocketAsyncEventArgs> m_pool;

        public IList<SocketAsyncEventArgs> getPools
        {
            get
            {
                return m_pool.ToList();
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="capacity">堆栈长度</param>
        public SocketAsyncEventArgsPool(int capacity)
        {
            m_pool = new Queue<SocketAsyncEventArgs>(capacity);
        }

        /// <summary>
        /// 将SocketAsyncEventArgs对像存入堆栈
        /// </summary>
        /// <param name="args">SocketAsyncEventArgs</param>
        public void Push(SocketAsyncEventArgs args)
        {
            if (args == null)
            {
                LogHelper.WriteError(this.GetType(), "SocketAsyncEventArgs资源已耗尽！当前使用：" + m_pool.Count);
            }
            lock (args)
            {
                m_pool.Enqueue(args);
            }
        }

        /// <summary>
        /// 将一个SocketAsyncEvent弹出堆栈
        /// </summary>
        /// <returns>SocketAsyncEventArgs</returns>
        public SocketAsyncEventArgs Pop()
        {
            lock (m_pool)
            {
                return m_pool.Dequeue();
            }
        }

        /// <summary>
        /// 获取堆栈当前数量
        /// </summary>
        public int Count
        {
            get { return m_pool.Count; }
        }
    }
}
